package kxfang.com.common.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;


import androidx.lifecycle.Observer;

//import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import kxfang.com.base.livedatabus.LiveDatabus;
import kxfang.com.base.utils.GsonUtils;
import kxfang.com.common.bean.OrderPayModel;
import kxfang.com.common.bean.PayResult;
import kxfang.com.common.config.HttpConfig;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.databus.EventCode;
import kxfang.com.common.databus.MastEvent;
import kxfang.com.common.dialog.MessageDialog;
import kxfang.com.common.dialog.WaitDialog;
import kxfang.com.common.parameter.AliPayPar;
import kxfang.com.common.parameter.UpdateOrderStatus;
import kxfang.com.common.views.BaseDialog;
import kxfang.com.http.EasyHttp;
import kxfang.com.http.callback.SimpleCallBack;
import kxfang.com.http.exception.ApiException;


/**
 * 支付
 */
public class PayUtil {
    private boolean needAgain;// 是否需要再次支付
    private OrderPayModel payModel;// 订单信息
    private PayListener payListener;// 成功回调监听
    private Activity context;
    private int payType;// 支付方式
    private CompositeDisposable mCompositeDisposable;
    private boolean isFinish = false;
    private Observer<MastEvent> observer;
    private WaitDialog.Builder waitDialog;

    public PayUtil(Activity activity, int payType, boolean needAgain, OrderPayModel payModel, PayListener payListener) {
        this.context = activity;
        this.payType = payType;
        this.needAgain = needAgain;
        this.payModel = payModel;
        this.payListener = payListener;
        waitDialog = new WaitDialog.Builder(context);
        onPayResult();
        toPay(payModel, payType);
    }



    private void toPay(OrderPayModel model, int payType) {
        waitDialog.setMessage("获取支付信息...").show();
        AliPayPar payPar = new AliPayPar();
        payPar.setBody(model.getBody());
        payPar.setSubject(model.getSubject());
        payPar.setTotalAmount(model.getTotalAmount());
        payPar.setOrderNo(model.getOrderNo());
        payPar.setExtra(model.getExtra());
        payPar.setMchid(model.getMchid());//1567005231
        EasyHttp.post(payType == Constant.PayConstants.WX_PAY ? HttpConfig.getWxPay : HttpConfig.getAliPay)
                .cacheKey(payType == Constant.PayConstants.WX_PAY ? HttpConfig.getWxPay : HttpConfig.getAliPay)
                .upJson(GsonUtils.toJson(payPar))
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        if (payListener != null) {
                            payListener.onWxSuccess(false);
                        }
                    }

                    @Override
                    public void onSuccess(String s) {
                        if (payType == Constant.PayConstants.WX_PAY) {
                            if (!WxUtil.getIwxApi(context).isWXAppInstalled()) {
                                ToastUtils.showShort("未安装微信！");
                                if (payListener != null) {
                                    payListener.onWxSuccess(false);
                                }
                                return;
                            }
                            wxPay(s);
                        } else if (payType == Constant.PayConstants.ALI_PAY) {
                            aliPay(s);
                        }

                    }

                    @Override
                    public void onCompleted() {
                        waitDialog.dismiss();
                    }
                });

    }

    /**
     * 微信支付
     */
    public void wxPay(String model) {
        try {
            JSONObject json = new JSONObject(model);
            PayReq req = new PayReq();
            req.appId = json.getString("appid");
            req.partnerId = json.getString("partnerid");
            req.prepayId = json.getString("prepayid");
            req.nonceStr = json.getString("nonceStr");
            req.timeStamp = json.getString("timestamp");
            req.packageValue = json.getString("package");
            req.sign = json.getString("sign");
            WxUtil.getIwxApi(context).sendReq(req);
        } catch (JSONException e) {
            ToastUtils.showShort("数据解析异常,调起微信支付失败");
        }

    }

    /**
     * 支付宝支付
     */
    public void aliPay(String model) {
//        final Runnable payRunnable = () -> {
//            PayTask alipay = new PayTask(context);
//            Map<String, String> result = alipay.payV2(model, true);
//            Log.i("msp", result.toString());
//
//            Message msg = new Message();
//            msg.what = Constant.PayConstants.SDK_PAY_FLAG;
//            msg.obj = result;
//            mHandler.sendMessage(msg);
//        };
//
//        // 必须异步调用
//        Thread payThread = new Thread(payRunnable);
//        payThread.start();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.PayConstants.SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        if (payListener != null) {
                            payListener.onAliSuccess(true);
                        }
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtils.showShort("支付成功");
                        updatePayStatus();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        if (payListener != null) {
                            payListener.onAliSuccess(false);
                        }
                        if (needAgain) {
                            againPay();
                        }
                        ToastUtils.showShort("支付失败");
                    }
                    break;
                default:
                    break;
            }
        }
    };


    public void onPayResult() {
        observer = event -> {
            switch (event.getCode().toString()) {
                case EventCode.PAY_WX_CODE:// 微信支付成功
                    if (payListener != null) {
                        payListener.onWxSuccess(true);
                    }
                    ToastUtils.showShort("支付成功");
                    updatePayStatus();
                    break;
                case EventCode.PAY_WX_CODE1:// 取消支付
                case EventCode.PAY_WX_CODE2:// 支付失败
                    if (payListener != null) {
                        payListener.onWxSuccess(false);
                    }
                    if (needAgain) {
                        againPay();
                    }
                    ToastUtils.showShort(event.getObj().toString());
                    break;
                default:
                    break;
            }
        };
        LiveDatabus.getInstance().with("支付回调",MastEvent.class).observeForever(observer);

        isFinish = true;
    }

    private void updatePayStatus() {
        UpdateOrderStatus status = new UpdateOrderStatus();
        status.setOrderNo(payModel.getOrderNo());
        status.setPayType(payType + "");
        status.setExtra(payModel.getExtra());
        EasyHttp.post(HttpConfig.updatePayStatus)
                .cacheKey(HttpConfig.updatePayStatus)
                .upJson(GsonUtils.toJson(status))
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onSuccess(String s) {
                        if (payListener != null) {
                            payListener.onUpdateStatus();
                        }
                    }
                });
    }

    /**
     * 再次发起支付
     */
    private void againPay() {
        new MessageDialog.Builder(context)
                .setTitle("温馨提示")
                .setMessage("订单支付失败，是否重新支付？")
                .setCancel("我再想想")
                .setConfirm("去支付")
                .setAutoDismiss(true)
                .setListener(dialog -> toPay(payModel, payType)).show();

    }


    /**
     * 网络请求相关
     */
    private <T> void addSubscription(Observable<T> observable, DisposableObserver<T> observer) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(observer);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    /**
     * 释放
     */
    public void clearDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
            mCompositeDisposable = null;
        }
        LiveDatabus.getInstance().with("支付回调",MastEvent.class).removeObserver(observer);

    }

    public interface PayListener {
        void onWxSuccess(boolean isSuccess);

        void onAliSuccess(boolean isSuccess);

        void onUpdateStatus();
    }
}
